﻿using BLL;
using InfoSoftGlobal;
using Model;
using System;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.StatisticalSum
{
    public partial class DayInterestReport : System.Web.UI.Page
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hidCompanyId.Value = (HttpContext.Current.Session["SysUserInfo"] as Sys_User).USER_COMPANY.ToString();
                //显示年份
                int year = DateTime.Now.Year;
                for (int i = year; i >= 1900; i--)
                {
                    ddlYear.Items.Add(new ListItem(i.ToString()));
                }
                ddlYear.SelectedValue = year.ToString();

                //显示季度
                DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));

                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                }
                else if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                }
                else if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-12-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                }
                else
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                    ListItem item3 = new ListItem("第四季", "9.21-12.20");
                    ddlNum.Items.Add(item3);
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindInit();
            InitZzt();
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public DataTable BindInit()
        {
            string year = ddlYear.SelectedValue.ToString();
            string month = ddlNum.SelectedValue.ToString().Split('-')[0].ToString().Replace('.', '-');
            string eMonth = ddlNum.SelectedValue.ToString().Split('-')[1].ToString().Replace('.', '-');

            string condition = " and 1=1";
            string start = "";
            if (month == "12-21")
            {
                string y = Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-1-1").AddYears(-1).ToString("yyyy");
                start = y + "-" + month;
            }
            else
            {
                start = year + "-" + month;
            }
            string end = year + "-" + eMonth;
            condition += "  and trunc(d.bdate) between to_date('" + start + "','yyyy-MM-dd')  and to_Date('" + end + "','yyyy-MM-dd') ";

            if (this.hidCompanyId.Value != "")
            {
                condition += " and d.companyid in(" + this.hidCompanyId.Value.ToString() + ")  ";
            }
            this.printargs.Value = condition;

            DataTable dt = new Yx_DayInterestBLL().SelectReprot(condition);
            DataTable dtt = dt.Copy();
            DataRow[] dr1 = dtt.Select(" 公司名称 <>'合计'");
            DataRow[] dr2 = dtt.Select(" 公司名称='合计'");
            foreach (DataRow item in dr2)
            {
                string s = item["利息合计"].ToString();
                item["利息合计"] = s.Trim().ToString() == "" ? "0" : s.Trim().ToString();
                break;
            }
            //收入户
            decimal syh = 0;
            //支出户
            decimal zch = 0;
            foreach (DataRow item in dr1)
            {
                syh += Convert.ToDecimal(item["收入户"].ToString());
                zch += Convert.ToDecimal(item["支出户"].ToString());
            }
            dtt.Rows[dtt.Rows.Count - 1]["收入户"] = syh.ToString();
            dtt.Rows[dtt.Rows.Count - 1]["支出户"] = zch.ToString();
            ViewState["database"] = dtt;
            gvReport.DataSource = dtt;
            gvReport.DataBind();
            return dt;
        }

        #region 导出文件

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOutput_Click(object sender, EventArgs e)
        {
            string fileName = "日利息统计_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string str = "导出人：" + (HttpContext.Current.Session["SysUserInfo"] as Sys_User).USER_NAME + "&nbsp;&nbsp;&nbsp;导出时间：" + DateTime.Now;
            lblTJ.Text = str;
            ExportExcel(pnl, fileName);
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="objControl"></param>
        /// <param name="strFileName"></param>
        public void ExportExcel(System.Web.UI.WebControls.WebControl objControl, string strFileName)
        {
            strFileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "gb2312";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//gb2312
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            objControl.RenderControl(oHtmlTextWriter);

            objControl = null;
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace("<td", "<td STYLE='MSO-NUMBER-FORMAT:\\@'"));
            System.Web.HttpContext.Current.Response.Buffer = false;
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

        #endregion 导出文件

        #region 画图方法

        public DataTable SelectSt(string condition)
        {
            string sql = string.Format(@" select cmy_name 公司名称,收入户 收入户,支出户 支出户,(收入户-支出户) 利息合计 from (
               select  d.companyid,c.cmy_name,nvl(sum(decode(d.accounttype,'2',d.createdayinterest,null)),0) 收入户,
               nvl(sum(decode(d.accounttype,'1',d.createdayinterest,null)),0) 支出户
               from yx_dayinterest d,sys_company c
               where d.companyid=c.cmy_id  and 1=1 " + condition + @"
               group by  d.companyid,c.cmy_name order by d.companyid ) ");
            DataTable dt = new BaseBLL().Query(sql);
            return dt;
        }

        /// <summary>
        /// 显示柱状图
        /// </summary>
        public void InitZzt()
        {
            string condition = this.printargs.Value.ToString();
            DataTable dt = SelectSt(condition);
            StringBuilder strXML = new StringBuilder();

            if (dt != null && dt.Rows.Count > 0)
            {
                strXML.Append("<chart caption='日利息统计图'  shownames='1'  numberSuffix='元' baseFont='仿宋' baseFontSize='12' palette='1' formatNumberScale='0'>");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strXML.AppendFormat("<set label='{0}' value='{1}'/>", dt.Rows[i]["公司名称"].ToString(), dt.Rows[i]["利息合计"].ToString());
                }

                strXML.Append("</chart>");
                string outPut = "";

                outPut = FusionCharts.RenderChartHTML("../Flash/Column3D.swf", "", strXML.ToString(), "billStatistics", "100%", "400", false, false);
                pnlZZT.Controls.Clear();
                pnlZZT.Controls.Add(new LiteralControl(outPut));
            }
        }

        #endregion 画图方法

        /// <summary>
        /// 根据年份显示季度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlYear.SelectedValue.ToString() != DateTime.Now.Year.ToString())
            {
                ddlNum.Items.Clear();
                ListItem item = new ListItem("第一季", "12.21-3.20");
                ddlNum.Items.Add(item);
                ListItem item1 = new ListItem("第二季", "3.21-6.20");
                ddlNum.Items.Add(item1);
                ListItem item2 = new ListItem("第三季", "6.21-9.20");
                ddlNum.Items.Add(item2);
                ListItem item3 = new ListItem("第四季", "9.21-12.20");
                ddlNum.Items.Add(item3);
            }
            else
            {
                ddlNum.Items.Clear();
                DateTime time = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-12-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                    ListItem item3 = new ListItem("第四季", "");
                    ddlNum.Items.Add(item3);
                }
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-3-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                }
                if (time >= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-6-21") && time <= Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-9-20"))
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                }
                else
                {
                    ListItem item = new ListItem("第一季", "12.21-3.20");
                    ddlNum.Items.Add(item);
                    ListItem item1 = new ListItem("第二季", "3.21-6.20");
                    ddlNum.Items.Add(item1);
                    ListItem item2 = new ListItem("第三季", "6.21-9.20");
                    ddlNum.Items.Add(item2);
                }
            }
        }

        #region 打印

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            #region 打印数据

            try
            {
                Response.Cookies["title"].Value = " 日~利~息~统~计@元";
                DataTable dt = (DataTable)ViewState["database"];
                if (dt == null)
                {
                    this.Page.RegisterClientScriptBlock("key", "<script>alert('请先点击查询！！')</script>");
                    return;
                }
                Session["DataBase"] = dt;

                ViewState.Remove("database");
                ClientScript.RegisterStartupScript(GetType(), "PrintRep", "PrintRep()", true);
            }
            catch (Exception)
            {
                this.Page.RegisterClientScriptBlock("key", "<script>alert('请先点击查询！！')</script>");
            }

            #endregion 打印数据
        }

        #endregion 打印

        /// <summary>
        /// GridView标题列排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvReport_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;
            BindProjectName(true);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            string year = ddlYear.SelectedValue.ToString();
            string month = ddlNum.SelectedValue.ToString().Split('-')[0].ToString().Replace('.', '-');
            string eMonth = ddlNum.SelectedValue.ToString().Split('-')[1].ToString().Replace('.', '-');

            string condition = " and 1=1";
            string start = "";
            if (month == "12-21")
            {
                string y = Convert.ToDateTime(ddlYear.SelectedValue.ToString() + "-1-1").AddYears(-1).ToString("yyyy");
                start = y + "-" + month;
            }
            else
            {
                start = year + "-" + month;
            }
            string end = year + "-" + eMonth;
            condition += "  and trunc(d.bdate) between to_date('" + start + "','yyyy-MM-dd')  and to_Date('" + end + "','yyyy-MM-dd') ";

            if (this.hidCompanyId.Value != "")
            {
                condition += " and d.companyid in(" + this.hidCompanyId.Value.ToString() + ")  ";
            }
            this.printargs.Value = condition;

            DataTable dt = new Yx_DayInterestBLL().SelectReprot(condition);
            DataTable dtt = dt.Copy();
            DataRow[] dr1 = dtt.Select(" 公司名称 <>'合计'");
            DataRow[] dr2 = dtt.Select(" 公司名称='合计'");
            foreach (DataRow item in dr2)
            {
                string s = item["利息合计"].ToString();
                item["利息合计"] = s.Trim().ToString() == "" ? "0" : s.Trim().ToString();
                break;
            }
            //收入户
            decimal syh = 0;
            //支出户
            decimal zch = 0;
            foreach (DataRow item in dr1)
            {
                syh += Convert.ToDecimal(item["收入户"].ToString());
                zch += Convert.ToDecimal(item["支出户"].ToString());
            }
            dtt.Rows[dtt.Rows.Count - 1]["收入户"] = syh.ToString();
            dtt.Rows[dtt.Rows.Count - 1]["支出户"] = zch.ToString();
            ViewState["database"] = dtt;
            gvReport.DataSource = dtt;
            gvReport.DataBind();

            InitZzt(); //柱状图

            DataView view = dt.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            gvReport.DataSource = view;

            gvReport.DataBind();
        }
    }
}